"""智能错误处理模块

提供统一的错误处理、智能分类、自动恢复、监控告警和性能影响分析。
包含错误预测、根因分析和自适应恢复策略。"""

import logging
import traceback
import functools
import json
import time
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List, Union, Callable, Type
from enum import Enum
from collections import defaultdict, deque
from dataclasses import dataclass, field


class ErrorType(Enum):
    """错误类型枚举"""
    VALIDATION_ERROR = "validation_error"
    PARSING_ERROR = "parsing_error"
    ALGORITHM_ERROR = "algorithm_error"
    STORAGE_ERROR = "storage_error"
    NETWORK_ERROR = "network_error"
    SYSTEM_ERROR = "system_error"
    USER_INPUT_ERROR = "user_input_error"
    CONFIGURATION_ERROR = "configuration_error"


class ErrorSeverity(Enum):
    """错误严重程度"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"
    EMERGENCY = "emergency"


class ErrorCategory(Enum):
    """错误类别"""
    VALIDATION = "validation"
    COMPUTATION = "computation"
    NETWORK = "network"
    RESOURCE = "resource"
    ALGORITHM = "algorithm"
    DATA = "data"
    SYSTEM = "system"
    SECURITY = "security"
    UNKNOWN = "unknown"


class RecoveryStrategy(Enum):
    """恢复策略"""
    RETRY = "retry"
    FALLBACK = "fallback"
    SKIP = "skip"
    ABORT = "abort"
    MANUAL = "manual"
    AUTO_HEAL = "auto_heal"


@dataclass
class ErrorInfo:
    """增强错误信息"""
    error_type: str
    message: str
    severity: ErrorSeverity
    category: ErrorCategory
    timestamp: datetime
    context: Dict[str, Any]
    stack_trace: Optional[str] = None
    recovery_suggestion: Optional[str] = None
    error_id: Optional[str] = None
    correlation_id: Optional[str] = None
    user_impact: Optional[str] = None
    business_impact: Optional[str] = None
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class ErrorPattern:
    """错误模式"""
    pattern_id: str
    error_signature: str
    frequency: int
    first_occurrence: datetime
    last_occurrence: datetime
    affected_components: List[str]
    recovery_success_rate: float
    recommended_strategy: RecoveryStrategy


@dataclass
class RecoveryAction:
    """恢复动作"""
    action_id: str
    strategy: RecoveryStrategy
    description: str
    execution_time: datetime
    success: bool
    duration: float
    side_effects: List[str] = field(default_factory=list)
    metadata: Dict[str, Any] = field(default_factory=dict)


class MCPError(Exception):
    """MCP服务自定义异常类"""
    
    def __init__(self, 
                 message: str,
                 error_type: ErrorType = ErrorType.SYSTEM_ERROR,
                 severity: ErrorSeverity = ErrorSeverity.MEDIUM,
                 suggestions: List[str] = None,
                 context: Dict[str, Any] = None):
        super().__init__(message)
        self.message = message
        self.error_type = error_type
        self.severity = severity
        self.suggestions = suggestions or []
        self.context = context or {}
        self.timestamp = datetime.now()


class EnhancedErrorHandler:
    """增强错误处理器"""
    
    def __init__(self, component_name: str = "mcp_service"):
        self.component_name = component_name
        self.logger = logging.getLogger(f"{__name__}.{component_name}")
        self._setup_logger()
        
        # 错误统计（按类别和严重程度）
        self.error_counts = defaultdict(lambda: defaultdict(int))
        self.error_rates = defaultdict(float)
        
        # 错误历史和模式
        self.error_history = deque(maxlen=10000)
        self.error_patterns = {}
        
        # 智能恢复策略
        self.recovery_strategies = {
            ErrorCategory.VALIDATION: self._handle_validation_error,
            ErrorCategory.COMPUTATION: self._handle_computation_error,
            ErrorCategory.RESOURCE: self._handle_resource_error,
            ErrorCategory.NETWORK: self._handle_network_error,
            ErrorCategory.ALGORITHM: self._handle_algorithm_error,
            ErrorCategory.DATA: self._handle_data_error,
            ErrorCategory.SYSTEM: self._handle_system_error,
            ErrorCategory.SECURITY: self._handle_security_error
        }
        
        # 恢复动作历史
        self.recovery_history = deque(maxlen=1000)
        
        # 错误阈值配置
        self.error_thresholds = {
            'error_rate_warning': 0.05,
            'error_rate_critical': 0.15,
            'consecutive_errors_warning': 5,
            'consecutive_errors_critical': 10,
            'pattern_frequency_threshold': 3
        }
        
        self.error_stats = {
            'total_errors': 0,
            'errors_by_type': {},
            'errors_by_severity': {},
            'recent_errors': []
        }
    
    def _setup_logger(self):
        """设置日志记录器"""
        if not self.logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
            self.logger.setLevel(logging.INFO)
    
    def handle_error(self, error: Exception, context: Dict[str, Any] = None, 
                    severity: ErrorSeverity = None, category: ErrorCategory = None,
                    correlation_id: str = None, user_friendly: bool = True) -> Union[ErrorInfo, str]:
        """智能错误处理"""
        if context is None:
            context = {}
        
        # 智能分类和严重程度评估
        if category is None:
            category = self._classify_error(error, context)
        if severity is None:
            severity = self._assess_severity(error, category, context)
        
        # 生成错误ID
        error_id = self._generate_error_id(error, context)
        
        # 创建增强错误信息
        error_info = ErrorInfo(
            error_type=type(error).__name__,
            message=str(error),
            severity=severity,
            category=category,
            timestamp=datetime.now(),
            context=context,
            stack_trace=traceback.format_exc(),
            error_id=error_id,
            correlation_id=correlation_id,
            user_impact=self._assess_user_impact(error, severity),
            business_impact=self._assess_business_impact(error, severity),
            metadata={
                'component': self.component_name,
                'thread_id': context.get('thread_id'),
                'request_id': context.get('request_id')
            }
        )
        
        # 记录错误统计
        self.error_stats['total_errors'] += 1
        
        if isinstance(error, MCPError):
            error_type = error.error_type.value
            severity_val = error.severity.value
            suggestions = error.suggestions
            error_context = error.context
        else:
            error_type = ErrorType.SYSTEM_ERROR.value
            severity_val = severity.value
            suggestions = []
            error_context = context or {}
        
        # 更新统计信息
        self.error_stats['errors_by_type'][error_type] = \
            self.error_stats['errors_by_type'].get(error_type, 0) + 1
        self.error_stats['errors_by_severity'][severity_val] = \
            self.error_stats['errors_by_severity'].get(severity_val, 0) + 1
        
        # 记录最近错误
        error_record = {
            'timestamp': datetime.now(),
            'type': error_type,
            'severity': severity_val,
            'message': str(error),
            'context': error_context
        }
        self.error_stats['recent_errors'].append(error_record)
        
        # 只保留最近50个错误
        if len(self.error_stats['recent_errors']) > 50:
            self.error_stats['recent_errors'] = self.error_stats['recent_errors'][-50:]
        
        # 记录日志
        self._log_error(error_info)
        
        # 更新统计
        self._update_error_statistics(error_info)
        
        # 添加到历史
        self.error_history.append(error_info)
        
        # 模式检测
        self._detect_error_patterns(error_info)
        
        # 智能恢复
        recovery_action = self._attempt_intelligent_recovery(error_info)
        
        # 性能影响分析
        self._analyze_performance_impact(error_info)
        
        # 预测分析
        self._update_error_predictions(error_info)
        
        # 告警检查
        self._check_error_thresholds(error_info)
        
        # 生成用户友好的错误信息
        if user_friendly:
            return self._generate_user_friendly_message(error_info)
        else:
            return error_info
    
    def _classify_error(self, error: Exception, context: Dict[str, Any]) -> ErrorCategory:
        """智能错误分类"""
        error_type = type(error).__name__.lower()
        error_message = str(error).lower()
        
        # 基于异常类型的分类
        if 'validation' in error_type or 'value' in error_type:
            return ErrorCategory.VALIDATION
        elif 'computation' in error_type or 'calculation' in error_type or 'math' in error_type:
            return ErrorCategory.COMPUTATION
        elif 'network' in error_type or 'connection' in error_type or 'timeout' in error_type:
            return ErrorCategory.NETWORK
        elif 'memory' in error_type or 'resource' in error_type or 'limit' in error_type:
            return ErrorCategory.RESOURCE
        elif 'algorithm' in error_type or 'optimization' in error_type:
            return ErrorCategory.ALGORITHM
        elif 'data' in error_type or 'format' in error_type or 'parse' in error_type:
            return ErrorCategory.DATA
        elif 'permission' in error_type or 'access' in error_type or 'auth' in error_type:
            return ErrorCategory.SECURITY
        elif 'system' in error_type or 'os' in error_type:
            return ErrorCategory.SYSTEM
        
        # 基于错误消息的分类
        if any(keyword in error_message for keyword in ['invalid', 'validation', 'constraint']):
            return ErrorCategory.VALIDATION
        elif any(keyword in error_message for keyword in ['network', 'connection', 'timeout']):
            return ErrorCategory.NETWORK
        elif any(keyword in error_message for keyword in ['memory', 'resource', 'limit']):
            return ErrorCategory.RESOURCE
        elif any(keyword in error_message for keyword in ['algorithm', 'optimization', 'solver']):
            return ErrorCategory.ALGORITHM
        elif any(keyword in error_message for keyword in ['data', 'format', 'parse']):
            return ErrorCategory.DATA
        
        return ErrorCategory.UNKNOWN
    
    def _assess_severity(self, error: Exception, category: ErrorCategory, context: Dict[str, Any]) -> ErrorSeverity:
        """评估错误严重程度"""
        # 基于错误类型的基础严重程度
        base_severity = {
            ErrorCategory.SECURITY: ErrorSeverity.CRITICAL,
            ErrorCategory.SYSTEM: ErrorSeverity.HIGH,
            ErrorCategory.RESOURCE: ErrorSeverity.HIGH,
            ErrorCategory.ALGORITHM: ErrorSeverity.MEDIUM,
            ErrorCategory.COMPUTATION: ErrorSeverity.MEDIUM,
            ErrorCategory.NETWORK: ErrorSeverity.MEDIUM,
            ErrorCategory.DATA: ErrorSeverity.MEDIUM,
            ErrorCategory.VALIDATION: ErrorSeverity.LOW,
            ErrorCategory.UNKNOWN: ErrorSeverity.MEDIUM
        }.get(category, ErrorSeverity.MEDIUM)
        
        # 基于上下文调整严重程度
        if context.get('critical_operation', False):
            if base_severity == ErrorSeverity.LOW:
                base_severity = ErrorSeverity.MEDIUM
            elif base_severity == ErrorSeverity.MEDIUM:
                base_severity = ErrorSeverity.HIGH
            elif base_severity == ErrorSeverity.HIGH:
                base_severity = ErrorSeverity.CRITICAL
        
        # 基于错误频率调整
        error_signature = f"{type(error).__name__}:{str(error)[:100]}"
        recent_similar_errors = sum(1 for e in list(self.error_history)[-50:] 
                                  if f"{e.error_type}:{e.message[:100]}" == error_signature)
        
        if recent_similar_errors >= 5:
            if base_severity == ErrorSeverity.LOW:
                base_severity = ErrorSeverity.MEDIUM
            elif base_severity == ErrorSeverity.MEDIUM:
                base_severity = ErrorSeverity.HIGH
        
        return base_severity
    
    def _generate_error_id(self, error: Exception, context: Dict[str, Any]) -> str:
        """生成错误ID"""
        import hashlib
        
        error_signature = f"{type(error).__name__}:{str(error)}:{context.get('component', '')}"
        error_hash = hashlib.md5(error_signature.encode()).hexdigest()[:8]
        timestamp = int(time.time())
        
        return f"ERR_{timestamp}_{error_hash}"
    
    def _assess_user_impact(self, error: Exception, severity: ErrorSeverity) -> str:
        """评估用户影响"""
        impact_map = {
            ErrorSeverity.LOW: "用户体验轻微影响，功能基本正常",
            ErrorSeverity.MEDIUM: "用户体验中等影响，部分功能受限",
            ErrorSeverity.HIGH: "用户体验严重影响，主要功能不可用",
            ErrorSeverity.CRITICAL: "用户体验严重受损，服务基本不可用",
            ErrorSeverity.EMERGENCY: "服务完全不可用，用户无法访问"
        }
        return impact_map.get(severity, "影响程度未知")
    
    def _assess_business_impact(self, error: Exception, severity: ErrorSeverity) -> str:
        """评估业务影响"""
        impact_map = {
            ErrorSeverity.LOW: "业务影响轻微，可正常运营",
            ErrorSeverity.MEDIUM: "业务影响中等，部分流程受阻",
            ErrorSeverity.HIGH: "业务影响严重，关键流程中断",
            ErrorSeverity.CRITICAL: "业务影响极严重，可能造成损失",
            ErrorSeverity.EMERGENCY: "业务完全中断，紧急处理"
        }
        return impact_map.get(severity, "业务影响未知")
    
    def _log_error(self, error_info: ErrorInfo):
        """记录错误日志"""
        log_message = f"[{error_info.error_id}] {error_info.error_type}: {error_info.message}"
        
        if error_info.context:
            log_message += f" | Context: {json.dumps(error_info.context, default=str)}"
        
        if error_info.severity == ErrorSeverity.EMERGENCY:
            self.logger.critical(log_message)
        elif error_info.severity == ErrorSeverity.CRITICAL:
            self.logger.critical(log_message)
        elif error_info.severity == ErrorSeverity.HIGH:
            self.logger.error(log_message)
        elif error_info.severity == ErrorSeverity.MEDIUM:
            self.logger.warning(log_message)
        else:
            self.logger.info(log_message)
    
    def _update_error_statistics(self, error_info: ErrorInfo):
        """更新错误统计"""
        self.error_counts[error_info.category][error_info.severity] += 1
        
        # 计算错误率
        total_errors = sum(sum(severity_counts.values()) for severity_counts in self.error_counts.values())
        if total_errors > 0:
            for category, severity_counts in self.error_counts.items():
                category_total = sum(severity_counts.values())
                self.error_rates[category] = category_total / total_errors
    
    def _detect_error_patterns(self, error_info: ErrorInfo):
        """检测错误模式"""
        error_signature = f"{error_info.error_type}:{error_info.message[:100]}"
        
        if error_signature not in self.error_patterns:
            self.error_patterns[error_signature] = ErrorPattern(
                pattern_id=f"pattern_{len(self.error_patterns)}",
                error_signature=error_signature,
                frequency=1,
                first_occurrence=error_info.timestamp,
                last_occurrence=error_info.timestamp,
                affected_components=[self.component_name],
                recovery_success_rate=0.0,
                recommended_strategy=RecoveryStrategy.RETRY
            )
        else:
            pattern = self.error_patterns[error_signature]
            pattern.frequency += 1
            pattern.last_occurrence = error_info.timestamp
            
            # 更新推荐策略
            if pattern.frequency >= self.error_thresholds['pattern_frequency_threshold']:
                pattern.recommended_strategy = self._get_adaptive_strategy(pattern)
    
    def _get_adaptive_strategy(self, pattern: ErrorPattern) -> RecoveryStrategy:
        """获取自适应恢复策略"""
        # 基于历史成功率选择策略
        if pattern.recovery_success_rate > 0.8:
            return RecoveryStrategy.RETRY
        elif pattern.recovery_success_rate > 0.5:
            return RecoveryStrategy.FALLBACK
        elif pattern.frequency > 10:
            return RecoveryStrategy.AUTO_HEAL
        else:
            return RecoveryStrategy.MANUAL
    
    def _attempt_intelligent_recovery(self, error_info: ErrorInfo) -> Optional[RecoveryAction]:
        """智能错误恢复"""
        # 获取推荐的恢复策略
        error_signature = f"{error_info.error_type}:{error_info.message[:100]}"
        pattern = self.error_patterns.get(error_signature)
        
        if pattern:
            recommended_strategy = pattern.recommended_strategy
        else:
            recommended_strategy = self._get_default_strategy(error_info.category)
        
        # 执行恢复动作
        recovery_action = RecoveryAction(
            action_id=f"recovery_{error_info.error_id}_{int(time.time())}",
            strategy=recommended_strategy,
            description=f"Attempting {recommended_strategy.value} recovery for {error_info.error_type}",
            execution_time=datetime.now(),
            success=False,
            duration=0.0
        )
        
        start_time = time.time()
        
        try:
            # 执行对应的恢复策略
            if error_info.category in self.recovery_strategies:
                strategy_func = self.recovery_strategies[error_info.category]
                recovery_result = strategy_func(error_info, recommended_strategy)
                
                recovery_action.success = recovery_result
                recovery_action.duration = time.time() - start_time
                
                if recovery_result:
                    self.logger.info(f"Successfully recovered from {error_info.error_type} using {recommended_strategy.value}")
                    error_info.recovery_suggestion = f"Recovered using {recommended_strategy.value} strategy"
                else:
                    self.logger.warning(f"Recovery attempt failed for {error_info.error_type}")
                    
        except Exception as recovery_error:
            recovery_action.success = False
            recovery_action.duration = time.time() - start_time
            recovery_action.side_effects.append(f"Recovery error: {str(recovery_error)}")
            self.logger.error(f"Recovery strategy {recommended_strategy.value} failed: {recovery_error}")
        
        # 记录恢复动作
        self.recovery_history.append(recovery_action)
        
        # 更新模式的恢复成功率
        if pattern:
            self._update_pattern_success_rate(pattern, recovery_action.success)
        
        return recovery_action
    
    def _get_default_strategy(self, category: ErrorCategory) -> RecoveryStrategy:
        """获取默认恢复策略"""
        default_strategies = {
            ErrorCategory.VALIDATION: RecoveryStrategy.RETRY,
            ErrorCategory.COMPUTATION: RecoveryStrategy.FALLBACK,
            ErrorCategory.NETWORK: RecoveryStrategy.RETRY,
            ErrorCategory.RESOURCE: RecoveryStrategy.AUTO_HEAL,
            ErrorCategory.ALGORITHM: RecoveryStrategy.FALLBACK,
            ErrorCategory.DATA: RecoveryStrategy.RETRY,
            ErrorCategory.SYSTEM: RecoveryStrategy.MANUAL,
            ErrorCategory.SECURITY: RecoveryStrategy.ABORT,
            ErrorCategory.UNKNOWN: RecoveryStrategy.RETRY
        }
        return default_strategies.get(category, RecoveryStrategy.RETRY)
    
    def _update_pattern_success_rate(self, pattern: ErrorPattern, success: bool):
        """更新模式成功率"""
        # 简单的移动平均
        current_rate = pattern.recovery_success_rate
        new_rate = 1.0 if success else 0.0
        pattern.recovery_success_rate = (current_rate * 0.9) + (new_rate * 0.1)
    
    def _analyze_performance_impact(self, error_info: ErrorInfo):
        """分析性能影响"""
        # 记录错误对性能的影响
        impact_data = {
            'error_id': error_info.error_id,
            'timestamp': error_info.timestamp,
            'category': error_info.category.value,
            'severity': error_info.severity.value,
            'component': self.component_name
        }
        
        # 可以在这里添加更详细的性能影响分析
        self.logger.debug(f"Performance impact analysis: {impact_data}")
    
    def _update_error_predictions(self, error_info: ErrorInfo):
        """更新错误预测"""
        # 基于历史数据预测未来可能的错误
        # 这里可以实现更复杂的预测算法
        pass
    
    def _check_error_thresholds(self, error_info: ErrorInfo):
        """检查错误阈值"""
        # 检查错误率阈值
        category_rate = self.error_rates.get(error_info.category, 0)
        
        if category_rate > self.error_thresholds['error_rate_critical']:
            self.logger.critical(f"Critical error rate threshold exceeded for {error_info.category.value}: {category_rate:.2%}")
        elif category_rate > self.error_thresholds['error_rate_warning']:
            self.logger.warning(f"Warning error rate threshold exceeded for {error_info.category.value}: {category_rate:.2%}")
        
        # 检查连续错误
        recent_errors = list(self.error_history)[-10:]
        consecutive_errors = 0
        for error in reversed(recent_errors):
            if error.category == error_info.category:
                consecutive_errors += 1
            else:
                break
        
        if consecutive_errors >= self.error_thresholds['consecutive_errors_critical']:
            self.logger.critical(f"Critical consecutive errors threshold exceeded: {consecutive_errors}")
        elif consecutive_errors >= self.error_thresholds['consecutive_errors_warning']:
            self.logger.warning(f"Warning consecutive errors threshold exceeded: {consecutive_errors}")
    
    def _handle_validation_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理验证错误"""
        return ErrorRecoveryStrategies.validation_recovery(error_info, strategy)
    
    def _handle_computation_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理计算错误"""
        return ErrorRecoveryStrategies.computation_recovery(error_info, strategy)
    
    def _handle_resource_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理资源错误"""
        return ErrorRecoveryStrategies.resource_recovery(error_info, strategy)
    
    def _handle_network_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理网络错误"""
        return ErrorRecoveryStrategies.network_recovery(error_info, strategy)
    
    def _handle_algorithm_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理算法错误"""
        return ErrorRecoveryStrategies.algorithm_recovery(error_info, strategy)
    
    def _handle_data_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理数据错误"""
        return ErrorRecoveryStrategies.validation_recovery(error_info, strategy)  # 使用验证恢复策略
    
    def _handle_system_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理系统错误"""
        return ErrorRecoveryStrategies.resource_recovery(error_info, strategy)  # 使用资源恢复策略
    
    def _handle_security_error(self, error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """处理安全错误"""
        # 安全错误通常不应自动恢复
        return False

    def _generate_user_friendly_message(self, error_info: ErrorInfo) -> str:
        """生成用户友好的错误消息"""
        friendly_messages = {
            ErrorCategory.VALIDATION: "输入数据验证失败，请检查输入参数",
            ErrorCategory.COMPUTATION: "计算过程中出现错误，请稍后重试",
            ErrorCategory.NETWORK: "网络连接异常，请检查网络状态",
            ErrorCategory.RESOURCE: "系统资源不足，请稍后重试",
            ErrorCategory.ALGORITHM: "算法执行异常，请检查问题配置",
            ErrorCategory.DATA: "数据格式错误，请检查输入数据",
            ErrorCategory.SYSTEM: "系统内部错误，请联系管理员",
            ErrorCategory.SECURITY: "安全验证失败，请检查权限",
            ErrorCategory.UNKNOWN: "未知错误，请联系技术支持"
        }
        
        base_message = friendly_messages.get(error_info.category, "系统出现异常")
        
        if error_info.recovery_suggestion:
            return f"{base_message}。{error_info.recovery_suggestion}"
        else:
            return f"{base_message}。错误ID: {error_info.error_id}"
    
    def get_error_statistics(self) -> Dict[str, Any]:
        """获取错误统计信息"""
        total_errors = sum(sum(severity_counts.values()) for severity_counts in self.error_counts.values())
        
        return {
            'total_errors': total_errors,
            'error_counts_by_category': {cat.value: dict(counts) for cat, counts in self.error_counts.items()},
            'error_rates': {cat.value: rate for cat, rate in self.error_rates.items()},
            'top_error_patterns': sorted(
                [(pattern.error_signature, pattern.frequency) for pattern in self.error_patterns.values()],
                key=lambda x: x[1], reverse=True
            )[:10],
            'recovery_success_rate': self._calculate_overall_recovery_rate(),
            'recent_errors': len([e for e in self.error_history if (datetime.now() - e.timestamp).total_seconds() < 3600])
        }
    
    def _calculate_overall_recovery_rate(self) -> float:
        """计算整体恢复成功率"""
        if not self.recovery_history:
            return 0.0
        
        successful_recoveries = sum(1 for action in self.recovery_history if action.success)
        return successful_recoveries / len(self.recovery_history)
    
    def get_error_insights(self) -> Dict[str, Any]:
        """获取错误洞察"""
        insights = {
            'most_frequent_errors': self._get_most_frequent_errors(),
            'error_trends': self._analyze_error_trends(),
            'recovery_effectiveness': self._analyze_recovery_effectiveness(),
            'recommendations': self._generate_error_recommendations()
        }
        return insights
    
    def _get_most_frequent_errors(self) -> List[Dict[str, Any]]:
        """获取最频繁的错误"""
        pattern_frequencies = [(pattern.error_signature, pattern.frequency, pattern.recovery_success_rate) 
                             for pattern in self.error_patterns.values()]
        pattern_frequencies.sort(key=lambda x: x[1], reverse=True)
        
        return [{
            'error_signature': sig,
            'frequency': freq,
            'recovery_rate': rate
        } for sig, freq, rate in pattern_frequencies[:5]]
    
    def _analyze_error_trends(self) -> Dict[str, Any]:
        """分析错误趋势"""
        now = datetime.now()
        recent_errors = [e for e in self.error_history if (now - e.timestamp).total_seconds() < 86400]  # 24小时内
        
        hourly_counts = {}
        for error in recent_errors:
            hour = error.timestamp.hour
            hourly_counts[hour] = hourly_counts.get(hour, 0) + 1
        
        return {
            'errors_last_24h': len(recent_errors),
            'peak_error_hour': max(hourly_counts.items(), key=lambda x: x[1])[0] if hourly_counts else None,
            'error_distribution': hourly_counts
        }
    
    def _analyze_recovery_effectiveness(self) -> Dict[str, Any]:
        """分析恢复效果"""
        strategy_stats = {}
        for action in self.recovery_history:
            strategy = action.strategy.value
            if strategy not in strategy_stats:
                strategy_stats[strategy] = {'total': 0, 'successful': 0, 'avg_duration': 0}
            
            strategy_stats[strategy]['total'] += 1
            if action.success:
                strategy_stats[strategy]['successful'] += 1
            strategy_stats[strategy]['avg_duration'] += action.duration
        
        for stats in strategy_stats.values():
            if stats['total'] > 0:
                stats['success_rate'] = stats['successful'] / stats['total']
                stats['avg_duration'] /= stats['total']
        
        return strategy_stats
    
    def _generate_error_recommendations(self) -> List[str]:
        """生成错误处理建议"""
        recommendations = []
        
        # 基于错误率的建议
        for category, rate in self.error_rates.items():
            if rate > 0.1:  # 错误率超过10%
                recommendations.append(f"建议关注{category.value}类错误，错误率较高({rate:.1%})")
        
        # 基于恢复成功率的建议
        overall_recovery_rate = self._calculate_overall_recovery_rate()
        if overall_recovery_rate < 0.5:
            recommendations.append("建议优化错误恢复策略，当前恢复成功率较低")
        
        # 基于错误模式的建议
        frequent_patterns = [p for p in self.error_patterns.values() if p.frequency > 5]
        if frequent_patterns:
            recommendations.append("检测到频繁出现的错误模式，建议进行根因分析")
        
        return recommendations


class ErrorRecoveryStrategies:
    """错误恢复策略实现"""
    
    @staticmethod
    def validation_recovery(error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """验证错误恢复"""
        if strategy == RecoveryStrategy.RETRY:
            # 对于验证错误，通常需要用户修正输入
            return False
        elif strategy == RecoveryStrategy.FALLBACK:
            # 使用默认值或简化验证
            return True
        return False
    
    @staticmethod
    def computation_recovery(error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """计算错误恢复"""
        if strategy == RecoveryStrategy.RETRY:
            # 重试计算
            return True
        elif strategy == RecoveryStrategy.FALLBACK:
            # 使用备用算法
            return True
        return False
    
    @staticmethod
    def network_recovery(error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """网络错误恢复"""
        if strategy == RecoveryStrategy.RETRY:
            # 重试网络请求
            return True
        elif strategy == RecoveryStrategy.FALLBACK:
            # 使用缓存数据
            return True
        return False
    
    @staticmethod
    def resource_recovery(error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """资源错误恢复"""
        if strategy == RecoveryStrategy.AUTO_HEAL:
            # 自动清理资源
            import gc
            gc.collect()
            return True
        elif strategy == RecoveryStrategy.FALLBACK:
            # 降级服务
            return True
        return False
    
    @staticmethod
    def algorithm_recovery(error_info: ErrorInfo, strategy: RecoveryStrategy) -> bool:
        """算法错误恢复"""
        if strategy == RecoveryStrategy.FALLBACK:
            # 使用备用算法
            return True
        elif strategy == RecoveryStrategy.RETRY:
            # 调整参数重试
            return True
        return False


# 全局错误处理器实例
_global_error_handler = None

def get_error_handler(component_name: str = "global") -> EnhancedErrorHandler:
    """获取全局错误处理器实例"""
    global _global_error_handler
    if _global_error_handler is None:
        _global_error_handler = EnhancedErrorHandler(component_name)
    return _global_error_handler


def handle_error(error: Exception, context: Dict[str, Any] = None, user_friendly: bool = True) -> Union[ErrorInfo, str]:
    """全局错误处理函数"""
    handler = get_error_handler()
    return handler.handle_error(error, context or {}, user_friendly)


def error_handler_decorator(component_name: str = None, user_friendly: bool = True):
    """错误处理装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                context = {
                    'function': func.__name__,
                    'component': component_name or func.__module__,
                    'args': str(args)[:200],
                    'kwargs': str(kwargs)[:200]
                }
                return handle_error(e, context, user_friendly)
        return wrapper
    return decorator


def handle_mcp_error(func):
    """MCP错误处理装饰器"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except MCPError as e:
            # 直接重新抛出MCP错误
            raise e
        except Exception as e:
            # 将其他异常转换为MCP错误
            context = {
                'function': func.__name__,
                'module': func.__module__,
                'args': str(args)[:200] if args else '',
                'kwargs': str(kwargs)[:200] if kwargs else ''
            }
            
            # 创建适当的MCP错误
            if 'validation' in str(e).lower() or 'invalid' in str(e).lower():
                mcp_error = create_validation_error(
                    message=str(e),
                    suggestions=["请检查输入参数的格式和有效性"]
                )
            elif 'parse' in str(e).lower() or 'format' in str(e).lower():
                mcp_error = create_parsing_error(
                    message=str(e),
                    suggestions=["请检查输入数据的格式"]
                )
            elif 'algorithm' in str(e).lower() or 'optimization' in str(e).lower():
                mcp_error = create_algorithm_error(
                    message=str(e),
                    suggestions=["请检查问题配置或尝试其他算法"]
                )
            else:
                mcp_error = MCPError(
                    message=str(e),
                    error_type=ErrorType.SYSTEM_ERROR,
                    severity=ErrorSeverity.HIGH,
                    context=context,
                    suggestions=["请联系技术支持"]
                )
            
            raise mcp_error
    return wrapper


def create_validation_error(message: str, suggestions: List[str] = None) -> MCPError:
    """创建验证错误"""
    return MCPError(
        message=message,
        error_type=ErrorType.VALIDATION_ERROR,
        severity=ErrorSeverity.MEDIUM,
        suggestions=suggestions or []
    )


def create_parsing_error(message: str, suggestions: List[str] = None) -> MCPError:
    """创建解析错误"""
    return MCPError(
        message=message,
        error_type=ErrorType.PARSING_ERROR,
        severity=ErrorSeverity.MEDIUM,
        suggestions=suggestions or []
    )


def create_algorithm_error(message: str, suggestions: List[str] = None) -> MCPError:
    """创建算法错误"""
    return MCPError(
        message=message,
        error_type=ErrorType.ALGORITHM_ERROR,
        severity=ErrorSeverity.HIGH,
        suggestions=suggestions or []
    )